<?
include "mysql.php";
include "JSON.php";


$link = new mysqlconn;
$link = $link->conectar();

function json_from_array($array){
	$json = new Services_JSON();
	$aux = $json->encode($array);
	echo $aux;
}

function start($dni){

	if ($dni != '')	echo '1';
	else echo '0';
}

function diesDisponibles(){
	$aux = array();
	for ($i= 1;$i < 8;$i++){
		$calculo = strtotime("+".$i." days");
		$dyh = getdate($calculo); 
		$aux[] =  $dyh['year']."-".$dyh['mon']."-".$dyh['mday'];
	}
	echo json_from_array($aux);
}

function horesDisponibles($dia){ //data
	global $link;
	$horesdisponibles = array();
	$horesreservadas = array();
	$query =  mysql_query("SELECT * FROM reservas where data='$dia'",$link);	

	if (@mysql_num_rows($query) > 0)
		while ($row = mysql_fetch_array($query))
				$horesreservadas[] = $row['hora'];

	for ($i = 10; $i < 22;$i++)
		if (!in_array($i.":00:00",$horesreservadas))
			$horesdisponibles [] = $i.":00";	
	 
	echo json_from_array($horesdisponibles);
}

function anularReserva($dni, $dia, $hora){
	global $link;
	if (mysql_query("DELETE FROM reservas where dni='$dni',dia='$dia',hora='$hora'",$link))
	echo 1;
	else echo 0;
		
}
function misReservas($dni){ //data
	global $link;
	$misReservas = array();
	$query =  mysql_query("SELECT *,DATE_FORMAT(data,'%d/%m/%y') as data, TIME_FORMAT(hora,'%H:%i') as hora  FROM reservas where dni='$dni'",$link);	
	if (@mysql_num_rows($query) > 0){
		while ($row = mysql_fetch_array($query)){
				$aux = array();
				$aux['dia'] = $row['data'];
				$aux['hora'] = $row['hora'];
				$misReservas[] = $aux;
		}
	}
	echo json_from_array($misReservas);
}


function doReserva($dni,$data,$hora){
	global $link;
	if ($dni != '' and $data != '' and $hora != ''){
		$q = mysql_query("SELECT * FROM reservas where dni ='$dni' and data='$data' limit 1",$link);
		if (mysql_num_rows($q) < 1) {
			if (mysql_query("INSERT INTO reservas (dni,data,hora) VALUES ('$dni','$data','$hora')",$link)) echo 1;
			else echo 0;
		}
	} else echo 0;
}